package com.gather.orm;

import java.util.HashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 信息校验类
 */
public class CheckInfo {
    public static HashSet<User> USER_DATA = new HashSet<>(); // 用户数据

    // 构造方法
    public CheckInfo(HashSet<User> USER_DATA) {
        this.USER_DATA = USER_DATA;
    }

    // 检验用户信息，返回登录状态
    public String checkAction(String name, String pwd, String password, String email, String phone, String birthday) {
        StringBuilder result = new StringBuilder();
        int state = 1;
        // 判断密码
        if (!pwd.equals(password)) {
            state = 2;
            result.append("两次密码不一致！\r\n");
        }

        // 生日正则匹配
        if (birthday.length() != 10) {
            state =2;
            result.append("生日日期格式不对！\r\n");
        } else {
            // 正则匹配
            String checkBirthday = "^(\\d{2}|\\d{4})[-/](0?[1-9]|1[1,2])[-/](0?[1-9]|[12]\\d|3[01])$";
            Pattern compileBirthday = Pattern.compile(checkBirthday);
            Matcher matcher = compileBirthday.matcher(birthday);
            boolean matchesBirthday = matcher.matches();
            if (!matchesBirthday) {
                state =2;
                result.append("生日日期格式不对！\r\n");
            }
        }
        // 手机号
        if (phone.length() != 11) {
            state =2;
            result.append("手机号格式不对！\r\n");
        } else {
            String checkPhone = "^(1[3,5,7,8])\\d{9}$";
            Pattern compilePhone = Pattern.compile(checkPhone);
            Matcher matcherPhone = compilePhone.matcher(phone);
            boolean matchesPhone = matcherPhone.matches();
            if (!matchesPhone) {
                state =2;
                result.append("手机期格式不对！\r\n");
            }
        }
        // 邮箱判断
        if(!email.contains("@")) {
            state =2;
            result.append("邮箱格式不对！\r\n");
        }
        // 以上信息确认无误，则将新用户加入到集合中
        if (state == 1) {
            // 把用户添加到集合中
            User user = new User(name,pwd,password,email,phone,birthday);
            if (USER_DATA.add(user)) {
                result.append("注册成功！");
            } else {
                state=2;
                result.append("用户已存在！");
            }
        }
        return result.toString();
    }
}
